#include"../include/stack.h"


// 检查栈是否为空
bool stack_is_empty(void *self) {
    Stack* stack= (Stack*)self;
    return stack->top == -1;
}

// 检查栈是否已满
bool stack_is_full(void *self) {
    Stack* stack= (Stack*)self;
    return stack->top == stack->capacity - 1;
}

// 压栈操作
bool stack_push(void *self, const void* element) {
    Stack* stack= (Stack*)self;
    if (stack_is_full(stack)) {
        // 容量翻倍扩容
        int new_capacity = stack->capacity * 2;
        void* new_data = realloc(stack->data, new_capacity * stack->element_size);
        if (!new_data) return false;
        
        stack->data = new_data;
        stack->capacity = new_capacity;
    }

    stack->top++;
    void* dest = (char*)stack->data + stack->top * stack->element_size;
    memcpy(dest, element, stack->element_size);
    return true;
}

// 弹栈操作
bool stack_pop(void *self) {
    Stack* stack= (Stack*)self;
    if (stack_is_empty(stack)) return false;
    stack->top--;
    return true;
}

// 查看栈顶元素
void* stack_peek(void *self) {
    Stack* stack= (Stack*)self;
    if (stack_is_empty(stack)) {
        return NULL;  // 空栈返回空指针
    }
    return (const char*)stack->data + stack->top * stack->element_size;
}

// 销毁栈
void stack_destroy(void *self) {
    Stack* stack= (Stack*)self;
    free(stack->data);
    free(stack);
}

// 创建栈
Stack* stack(size_t element_size) {
    Stack* stack = (Stack*)malloc(sizeof(Stack));
    if (!stack) return NULL;

    stack->element_size = element_size;
    stack->capacity = 1024;
    stack->top = -1;
    stack->data = malloc(element_size * 1024);
    stack->back=stack_peek;
    stack->clear=stack_destroy;
    stack->is_empty=stack_is_empty;
    stack->is_full=stack_is_full;
    stack->pop=stack_pop;
    stack->push=stack_push;

    if (!stack->data) {
        free(stack);
        return NULL;
    }
    return stack;
}
